<template>
  <div>
    <FormPanel ref="formpanel2" :list="formList2" labelWidth="120" :isSubmitBtn="false" @formChange="formchangeFuns" />
    <FilterTable
      ref="basetables"
      :columns="columns1"
      columnsRef="partPartInventoryAdjustInventoryEditPartPage"
      :dataSource="emptyTableData"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns1 => (this.columns1 = columns1)"
      :height="'200'"
      :onSyncTableData="tablechangeFun"
    ></FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9999,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button type="primary" @click="confirmHandle">确认</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>

    <!-- 库位选择弹窗 -->
    <BaseDialog title="选择库位" width="30%" :visible.sync="positionChoseVisible" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <position :params="positionSelectParam" @onConfirm="handlePositionSelectConfirm" @close="positionChoseVisible = false" />
    </BaseDialog>
  </div>
</template>
<script>
import { isAuthorized } from '@/utils/index';
import { getStorageList, getaddPartList, queryAllocateoutData } from '@/api/part/partInventory/adjustInventory/index';
import { getPosition } from '@/api/part/inventoryManager/inventoryManager/index';
import { dictionary } from '@/utils/dictMixin';
import position from '@/pages/part/common/position';

export default {
  components: {
    position
  },
  mixins: [dictionary],
  props: ['editRowData', 'billNo'],
  data() {
    this.basetables = null;
    return {
      formList2: this.createFroms(),
      fetchParams: {
        xhrAbort: true,
        sort: '',
        order: 'asc',
        limit: '10',
        offset: '0'
      },
      columns1: this.createTables(),
      emptyTableData: [], // 用于清空表格数据
      fromSubmitdata: {},
      positionChoseVisible: false, // 是否显示库位选择弹窗
      positionSelectParam: {}, // 库位选择弹窗数据
      billNoQuantity: 0 // 对应单号配件数量
    };
  },
  created() {
    this.getlist();
    // 还入对应单查询
    this.queryBillNo();
  },
  mounted() {
    this.basetables = this.$refs.basetables.$refs.pageTable;
    this.formList2.find(x => x.fieldName === 'STORAGE_CODE').initialValue = this.editRowData.STORAGE_CODE;
    this.formList2.find(x => x.fieldName === 'STORAGE_POSITION_CODE').initialValue = this.editRowData.STORAGE_POSITION_CODE;
    this.formList2.find(x => x.fieldName === 'partNo').initialValue = this.editRowData.PART_NO;
    this.formList2.find(x => x.fieldName === 'PART_NAME').initialValue = this.editRowData.PART_NAME;
    this.formList2.find(x => x.fieldName === 'IN_QUANTITY').initialValue = this.editRowData.IN_QUANTITY;
    this.formList2.find(x => x.fieldName === 'inPrice').initialValue = this.editRowData.IN_PRICE;
    this.formList2.find(x => x.fieldName === 'inAmount').initialValue = this.editRowData.IN_AMOUNT;
    // 获取库位的数据
    // this.queryEmptyLocation(this.editRowData.STORAGE_CODE);
    this.getpartlist(this.editRowData);
    this.handleQx();
  },
  methods: {
    async queryBillNo() {
      // 还入
      if (this.editRowData.ALLOCATE_TYPE && this.editRowData.ALLOCATE_TYPE == '82121002') {
        // 逻辑问题 当单子有多个件的时候只取第一个件会导致校验错误 hxj 2020-08-12
        let res = await queryAllocateoutData({ billNo: this.billNo });
        // console.log(this.editRowData, res, '查询结果');
        if (res.resultCode == 200) {
          if (res.data.rows && res.data.rows.length > 0 && res.data.rows.find(item => item.PART_NO == this.editRowData.PART_NO)) {
            this.billNoQuantity = res.data.rows.find(item => item.PART_NO == this.editRowData.PART_NO).IN_QUANTITY;
            // console.log('借出仓库数量', this.billNoQuantity);
          } else {
            this.billNoQuantity = this.editRowData.IN_QUANTITY;
          }
        }
        // this.billNoQuantity = this.editRowData.IN_QUANTITY;
      }
    },
    handleQx() {
      this.formList2.find(x => x.fieldName == 'STORAGE_POSITION_CODE').disabled = !isAuthorized('1313', '13131013');
    },
    async queryEmptyLocation(val) {
      let res = await getPosition({ storageCode: val });
      if (res.resultCode == 200) {
        if (res.data.length <= 0) {
          this.$notify.warning({ title: '错误提示', message: '该仓库中没有库位可以使用' });
        } else {
          this.formList2.find(item => item.fieldName == 'STORAGE_POSITION_CODE').itemList = res.data.map(x => ({ text: x.storagePositionCode, value: x.storagePositionCode }));
        }
      }
    },
    createFroms() {
      return [
        { type: 'SELECT', label: '仓库', fieldName: 'STORAGE_CODE', itemList: [], rules: [{ required: true, message: '请输入仓库', trigger: 'blur' }], disabled: true },
        {
          type: 'INPUT',
          label: '库位',
          fieldName: 'STORAGE_POSITION_CODE',
          itemList: [],
          readOnly: true,
          rules: [{ required: true, message: '请选择库位', trigger: 'blur' }],
          unitRender: () => {
            return <el-button icon="el-icon-search" onClick={this.handleChosePositionCode}></el-button>;
          }
        },

        { type: 'INPUT', label: '配件代码', fieldName: 'partNo', rules: [{ required: true, message: '请输入配件代码', trigger: 'blur' }], disabled: true },
        { type: 'INPUT', label: '配件名称', fieldName: 'PART_NAME', rules: [{ required: true, message: '请输入配件名称', trigger: 'blur' }], disabled: true },
        {
          type: 'INPUT_NUMBER',
          label: '入库数量',
          min: 0.01,
          fieldName: 'IN_QUANTITY',
          precision: 2,
          change: val => {
            this.changemNum(val);
          },
          rules: [{ required: true, message: '请输入入库数量', trigger: 'blur' }],
          disabled: false
        },
        {
          type: 'INPUT_NUMBER',
          label: '入库不含税单价',
          min: 0.01,
          fieldName: 'inPrice',
          change: val => {
            this.changemoney(val);
          },
          rules: [{ required: true, message: '请输入入库不含税单价', trigger: 'blur' }],
          disabled: false
        },
        { type: 'INPUT_NUMBER', label: '入库不含税金额', min: 0.01, fieldName: 'inAmount', rules: [{ required: true, message: '请输入入库不含税金额', trigger: 'blur' }], disabled: true }
      ];
    },
    createTables() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '销售价', dataIndex: 'SALES_PRICE', sorter: true, filter: true, filterType: 'input' },
        { title: '索赔价', dataIndex: 'CLAIM_PRICE', sorter: true, filter: true, filterType: 'input', hidden: !isAuthorized('1313', '13131006') },
        { title: '终端建议零售价格', dataIndex: 'INSURANCE_PRICE', sorter: true, filter: true, filterType: 'input' },
        { title: '最低销售限价', dataIndex: 'MIN_LIMIT_PRICE', sorter: true, filter: true, filterType: 'input' },
        { title: '销售限价', dataIndex: 'LIMIT_PRICE', sorter: true, filter: true, filterType: 'input' },
        { title: '最大库存', dataIndex: 'MAX_STOCK', sorter: true, filter: true, filterType: 'input' },
        { title: '最小库存', dataIndex: 'MIN_STOCK', sorter: true, filter: true, filterType: 'input' },
        { title: '账面库存', dataIndex: 'STOCK_QUANTITY', sorter: true, filter: true, filterType: 'input' },
        { title: '可用库存', dataIndex: 'USEABLE_STOCK', sorter: true, filter: true, filterType: 'input' },
        { title: '锁定量', dataIndex: 'LOCKED_QUANTITY', sorter: true, filter: true, filterType: 'input' },
        { title: '替代配件', dataIndex: 'OPTION_NO', sorter: true, filter: true, filterType: 'input' },
        { title: '替代件库存', dataIndex: 'OPTION_STOCK', sorter: true, filter: true, filterType: 'input' },
        {
          title: '配件类别',
          dataIndex: 'PART_GROUP_CODE',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{this.createDictText(props.row.PART_GROUP_CODE, '8075')}</span>;
          }
        },
        { title: '单位', dataIndex: 'UNIT_NAME', sorter: true, filter: true, filterType: 'input' }
      ];
    },
    // 获取数据字典数据
    async getlist() {
      this.formList2[0].itemList = (await getStorageList({})).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
    },
    formchangeFuns(val) {
      this.fromSubmitdata = val;
      let json = this.tableslist[0] || {};
      json.IN_QUANTITY = this.fromSubmitdata.IN_QUANTITY;
      json.IN_PRICE = this.fromSubmitdata.inPrice;
      json.IN_AMOUNT = this.fromSubmitdata.inAmount;
      json.FLAG = 'X';
      json.STORAGE_POSITION_CODE = this.formList2.find(x => x.fieldName === 'STORAGE_POSITION_CODE').initialValue;
      json.editIndex = this.editRowData.index;
      json.PART_NAME = this.fromSubmitdata.PART_NAME;
      // console.log('借出仓库数量', this.billNoQuantity);

      if (this.editRowData.ALLOCATE_TYPE == '82121002' && json.IN_QUANTITY > this.billNoQuantity) {
        return this.$notify.warning({ title: '提示信息', message: '还入入库数量不能大于借出出库数量' });
      }
      this.$emit('editPart', json);
    },
    async getpartlist(val) {
      this.emptyTableData = [];
      let res = (await getaddPartList(val.STORAGE_CODE, val.PART_NO)).data.rows;
      this.basetables.EXECUTE_INSERT(res);
    },
    changemoney(val) {
      let num = this.formList2.find(x => x.fieldName === 'IN_QUANTITY').initialValue;
      this.formList2.find(x => x.fieldName === 'inAmount').initialValue = (val * num).toFixed(2);
    },
    changemNum(val) {
      let money = this.formList2.find(x => x.fieldName === 'inPrice').initialValue;
      this.formList2.find(x => x.fieldName === 'inAmount').initialValue = (val * money).toFixed(2);
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('close', false);
    },
    tablechangeFun(val) {
      this.tableslist = val;
    },
    // 添加事件提交表单
    confirmHandle() {
      this.$refs.formpanel2.SUBMIT_FORM();
    },
    // 库位选择点击
    handleChosePositionCode() {
      let partNo = this.formList2.find(x => x.fieldName === 'partNo').initialValue;
      let storageCode = this.formList2.find(x => x.fieldName === 'STORAGE_CODE').initialValue;
      if (storageCode) {
        this.positionSelectParam = {
          storageCode,
          partNo
        };
        this.positionChoseVisible = true;
      } else {
        this.$notify.warning('请先选择仓库');
      }
    },
    // 库位选择点击确定
    handlePositionSelectConfirm(e) {
      let storageCode = this.formList2.find(item => item.fieldName == 'STORAGE_CODE').initialValue;
      let partNo = this.formList2.find(item => item.fieldName == 'partNo').initialValue;
      if (storageCode && partNo) {
        this.getpartlist({
          STORAGE_CODE: storageCode,
          PART_NO: partNo
        });
      }
      // console.log(e);
      this.formList2.find(x => x.fieldName === 'STORAGE_POSITION_CODE').initialValue = e[0].storagePositionCode;
      this.positionChoseVisible = false;
    }
  }
};
</script>
